<template>
  <div>
    <form-dialog ref="formDrawerRef" title="预检" top="5vh" width="90%" @submit="handleCheckReserve">
      <div class="dialog-body">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="3" border>
          <el-descriptions-item label="车主姓名" label-align="center" label-class-name="info-label">
            {{ curInfo.payStatus ? curInfo.customerName : curInfo.customer.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="车主电话" label-align="center" label-class-name="info-label">
            {{ curInfo.customerPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="车牌号" label-align="center" label-class-name="info-label">
            {{ curInfo.licensePlate }}
          </el-descriptions-item>
          <el-descriptions-item label="车架号(vin)" label-align="center" label-class-name="info-label">
            {{ curInfo.vin }}
          </el-descriptions-item>
          <el-descriptions-item label="车型" label-align="center" label-class-name="info-label">
            {{ curInfo.vehicleModel }}
          </el-descriptions-item>
          <el-descriptions-item label="接车公里数" label-align="center" label-class-name="info-label">
            {{ curInfo.mileageNum }}
          </el-descriptions-item>
          <el-descriptions-item label="保险到期日期" label-align="center" label-class-name="info-label">
            {{ curInfo.car.insuranceExpireTime }}
          </el-descriptions-item>
          <el-descriptions-item label="年检到期日期" label-align="center" label-class-name="info-label">
            {{ curInfo.car.annualExpireTime }}
          </el-descriptions-item>
          <el-descriptions-item label="燃料(能源类型)" label-align="center" label-class-name="info-label">
            {{ handleEnergyType(curInfo.energyType) }}
          </el-descriptions-item>
        </el-descriptions>
        <el-divider />
        <div class="mt-5 mb-2 text-[16px] font-bold">外观检查</div>
        <div class="flex flex-wrap">
          <div v-for="item in outProject" :key="item.id"
            class="relative flex items-center px-4 py-2 mr-4 mb-2 border-[1px] border-solid border-[#e5e5e5] rounded-[8px] cursor-pointer"
            :class="[item.isChoosed ? 'border-[var(--el-color-primary)] text-[var(--el-color-primary)]' : '']"
            @click="handleCheckOutChange(item)">
            <span>{{ item.name }}</span>
            <el-icon v-if="item.isChoosed" size="18" color="var(--el-color-primary)"
              class="absolute right-[-12px] top-[-8px]">
              <SuccessFilled />
            </el-icon>
          </div>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <el-card v-for="item in checkOutList" :key="item.name" :header="item.name">
            <el-form ref="formRef" :model="item" label-width="80px">
              <el-form-item label="隐患图片">
                <div>
                  <el-upload :limit="1" v-model:file-list="item.imgList" :data="{ item, type: 1 }"
                    list-type="picture-card" :http-request="handleUploadImg">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item label="隐患备注">
                <el-input v-model="item.dangerRemark" placeholder="请输入隐患备注" clearable style="width: 200px" />
              </el-form-item>
            </el-form>
          </el-card>
        </div>
        <el-divider />
        <div class="mt-5 mb-2 text-[16px] font-bold">内饰检查</div>
        <div class="flex flex-wrap">
          <div v-for="item in inProject" :key="item.id"
            class="relative flex items-center px-4 py-2 mr-4 mb-2 border-[1px] border-solid border-[#e5e5e5] rounded-[8px] cursor-pointer"
            :class="[item.isChoosed ? 'border-[var(--el-color-primary)] text-[var(--el-color-primary)]' : '']"
            @click="handleCheckInChange(item)">
            <span>{{ item.name }}</span>
            <el-icon v-if="item.isChoosed" size="18" color="var(--el-color-primary)"
              class="absolute right-[-12px] top-[-8px]">
              <SuccessFilled />
            </el-icon>
          </div>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <el-card v-for="item in checkInList" :key="item.name" :header="item.name">
            <el-form ref="formRef" :model="item" label-width="80px">
              <el-form-item label="隐患图片">
                <div>
                  <el-upload v-model:file-list="item.imgList" :data="{ item, type: 2 }" list-type="picture-card"
                    :http-request="handleUploadImg">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item label="隐患备注">
                <el-input v-model="item.dangerRemark" placeholder="请输入隐患备注" clearable style="width: 200px" />
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </div>
    </form-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import useRepairStore from "@/stores/modules/repair";
import { useInitForm } from "@/hooks/useCommon";
import FormDialog from "@/components/FormDialog.vue";
import { energyTypeList } from "@/enum/index";
import { uploadFileApi } from "@/api/user";
import { addExamineInfoApi } from "@/api/examine";
import { toast } from "@/utils/index";

const useRepair = useRepairStore();
// 当前选择维修单信息
const curInfo = ref<any>({});
// 预检
const { formDrawerRef, handleCreate } = useInitForm({});

// 外观检查项目
const outProject = ref<any[]>([]);
// 选中的外观检查
const checkOutList = ref<any[]>([]);

// 内饰检查项目
const inProject = ref<any[]>([]);
// 选中的内饰检查项目
const checkInList = ref<any[]>([]);

// 点击外观检查项
const handleCheckOutChange = (val: any) => {
  outProject.value.forEach((item) => {
    if (item.id === val.id) {
      item.isChoosed = !item.isChoosed;
    }
  });
  const curIndex = checkOutList.value.findIndex((item: any) => item.id === val.id);
  if (curIndex !== -1) {
    checkOutList.value.splice(curIndex, 1);
  } else {
    checkOutList.value.push(val);
  }
};
// 点击内饰检查项
const handleCheckInChange = (val: any) => {
  inProject.value.forEach((item) => {
    if (item.id === val.id) {
      item.isChoosed = !item.isChoosed;
    }
  });
  const curIndex = checkInList.value.findIndex((item: any) => item.id === val.id);
  if (curIndex !== -1) {
    checkInList.value.splice(curIndex, 1);
  } else {
    checkInList.value.push(val);
  }
};
// 图片上传
const handleUploadImg = async (params: any) => {
  const { data, file } = params;
  const { item, type } = data;
  const formData = new FormData();
  formData.append("file", file);
  const res: any = await uploadFileApi(formData);
  const curItem = type === 1 ? checkOutList.value : checkInList.value;
  curItem.forEach((item1: any) => {
    if (item1.id === item.id) {
      item1.dangerImg = res[0].accessUrl;
    }
  });
};

// 保存按钮
const handleCheckReserve = async () => {
  const curOutItem = checkOutList.value.map((item: any) => {
    return {
      precheckId: item.id,
      dangerImg: item.dangerImg,
      dangerRemark: item.dangerRemark
    };
  });
  const curInItem = checkInList.value.map((item: any) => {
    return {
      precheckId: item.id,
      dangerImg: item.dangerImg,
      dangerRemark: item.dangerRemark
    };
  });
  try {
    (formDrawerRef.value as any).showLoading();
    await addExamineInfoApi({
      repairOrderId: curInfo.value.id,
      precheckList: [...curOutItem, ...curInItem]
    });
    (formDrawerRef.value as any).close();
    toast("预检提交成功");
  } finally {
    (formDrawerRef.value as any).hideLoading();
  }
};

// 处理燃源类型
const handleEnergyType = (val: string | number) => {
  const curItem = energyTypeList.find((item: any) => item.value === val);
  return curItem ? curItem.label : "";
};

// 处理检查项目
const handleFilterProject = (val: any) => {
  const curItem = val.map((item: any) => ({
    id: item.id,
    name: item.precheckName,
    type: item.type,
    imgList: [],
    dangerImg: "",
    dangerRemark: "",
    isChoosed: false
  }));
  outProject.value = curItem.filter((item: any) => item.type === 1);
  inProject.value = curItem.filter((item: any) => item.type === 2);
};

// 处理预检内容回显
const handleReserveShow = (val: any) => {
  const outItem = val.filter((item: any) => item.type === 1);
  const inItem = val.filter((item: any) => item.type === 2);
  outProject.value.forEach((item) => {
    const curItem = outItem.find((it: any) => it.precheckId === item.id);
    if (curItem) {
      item.isChoosed = true;
    }
  });
  inProject.value.forEach((item) => {
    const curItem = inItem.find((it: any) => it.precheckId === item.id);
    if (curItem) {
      item.isChoosed = true;
    }
  });
  checkOutList.value = outItem.map((item: any) => {
    return {
      id: item.precheckId,
      name: item.precheckName,
      imgList: [
        {
          url: item.dangerImg
        }
      ],
      dangerImg: item.dangerImg,
      dangerRemark: item.dangerRemark
    };
  });
  checkInList.value = inItem.map((item: any) => {
    return {
      id: item.precheckId,
      name: item.precheckName,
      imgList: [{
        url: item.dangerImg
      }],
      dangerImg: item.dangerImg,
      dangerRemark: item.dangerRemark
    };
  });
};

// 当前选中的维修单
watch(
  () => useRepair.curOrder,
  (newVal) => {
    console.log(newVal)
    curInfo.value = newVal;
  },
  {
    immediate: true
  }
);
// 回显预检信息
watch([() => useRepair.examineList, () => useRepair.curReserveInfo], ([newVal1, newVal2]) => {
  if (newVal1.length) {
    handleFilterProject(newVal1);
    handleReserveShow(newVal2);
  }
});

defineExpose({
  handleCreate
});
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 200px);
  overflow-y: auto;

  :deep(.info-label) {
    width: 120px;
    font-weight: 700;
  }
}
</style>
